﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Collect_Request_Select : System.Web.UI.Page
    {
        IBLLPrePurchaseRequest bll = new PrePurchaseRequestBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        IBLLSysDurationCount bllDurationCount = new SysDurationCountBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        CollectRequestBLL bllCollectReq = new CollectRequestBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            IList<PrePurchaseRequestInfo> infoPprSelected = new List<PrePurchaseRequestInfo>();
            if (!IsPostBack)
            {
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
                rdbDuration.Attributes.Add("onclick", "return ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbDate.Attributes.Add("onclick", "return ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                LoadDurationType();
                LoadDurationCount();
                LoadDisplay();
                TipDuration.TargetControls.Add(Show_DurationRequired.ClientID, "", true);
                CalendarDate.FocusedDate = DateTime.Today;
                CalendarDate.SelectedDate = DateTime.Today;
            }
        }

        protected void LoadDurationType()
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            cbDurationType.DataSource = infoList;
            cbDurationType.DataBind();
        }

        protected void LoadDurationCount()
        {
            IList<SysDurationCountInfo> infoList = bllDurationCount.GetSysDurationCount();
            cbDurationCount.DataSource = infoList;
            cbDurationCount.DataBind();
        }

        protected void LoadDisplay()
        {
            IList<PrePurchaseRequestInfo> infoPprSelected = new List<PrePurchaseRequestInfo>(); 
            infoPprSelected = (List<PrePurchaseRequestInfo>)Session["infoPprSelected"];
            IList<PrePurchaseRequestInfo> infoDuration = bll.GetDuration(infoPprSelected);
            IList<PrePurchaseRequestInfo> infoName = bll.GetName(infoPprSelected);
            IList<PrePurchaseRequestInfo> infoReason = bll.GetReason(infoPprSelected);
            IList<string> DurationList = new List<string>();
            string[] YearTypeAndYear = infoPprSelected[0].YearTypeDescr.Split(' ');
            lblYearType.Text = YearTypeAndYear[0];
            lblBgmYear.Text = YearTypeAndYear[1];
            lblPcRule.Text = infoPprSelected[0].InfoPurchaseRule.Name;
            lblPcType.Text = infoPprSelected[0].InfoPurchaseType.Name;
            txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

            if (infoDuration.Count > 0)
            {
                if (infoDuration.Count == 1)
                {
                    if (infoDuration[0].DateRequired != null)
                    {
                        rdbDate.Checked = true;
                        txtDateReq.Text = (infoDuration[0].DateRequired != null) ? ((DateTime)infoDuration[0].DateRequired).ToString("dd/MM/yyyy") : "";
                        RadManager1.ResponseScripts.Add(@"ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                    }
                    if (infoDuration[0].DurationRequired != null)
                    {
                        txtDurationReq.Text = infoDuration[0].DurationRequired.ToString();
                        cbDurationType.SelectedValue = infoDuration[0].InfoDurationType.Seq.ToString();
                        cbDurationCount.SelectedValue = infoDuration[0].InfoDurationCount.Seq.ToString();
                        RadManager1.ResponseScripts.Add(@"ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                    }
                }
                else
                {
                    for (int i = 0; i < infoDuration.Count; i++)
                    {
                        string DurationDescr = "";
                        if (infoDuration[i].DurationRequired != null)
                        {
                            DurationDescr = "ภายใน " + infoDuration[i].DurationRequired + " " + infoDuration[i].InfoDurationType.Name + " นับจาก " + infoDuration[i].InfoDurationCount.Name;
                        }
                        else if (infoDuration[i].DateRequired != null)
                        {
                            DurationDescr = "ภายในวันที่ " + ((DateTime)infoDuration[i].DateRequired).ToString("dd/MM/yyyy");
                        }

                        DurationList.Add(DurationDescr);
                    }

                    Session["ListDuration"] = DurationList;
                }
            }
            else
            {
                rdbDuration.Checked = true;
                RadManager1.ResponseScripts.Add(@"ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
            }

            if (infoName.Count > 0)
            {
                for (int i = 0; i < infoName.Count; i++)
                {
                    if (i == 0)
                    {
                        txtName.Text = infoName[i].Name;
                    }
                    else
                    {
                        txtName.Text += " " + infoName[i].Name;
                    }
                }
            }

            if (infoReason.Count > 0)
            {
                for (int i = 0; i < infoReason.Count; i++)
                {
                    if (i == 0)
                    {
                        txtReason.Text = infoReason[i].Reason;
                    }
                    else
                    {
                        txtReason.Text += " " + infoReason[i].Reason;
                    }
                }
            }
        }

        protected void cbOperationName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                RadComboBox cbAppEmp = (RadComboBox)sender;
                cbAppEmp.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbAppEmp.Items[j].FindControl("tableOperationName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void OnAjaxUpdate_History(object sender, ToolTipUpdateEventArgs e)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_DurationList.ascx");
            e.UpdatePanel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void btnSendTo_Click(object sender, EventArgs e)
        {
            IList<PrePurchaseRequestInfo> infoPprSelected = new List<PrePurchaseRequestInfo>();
            infoPprSelected = (List<PrePurchaseRequestInfo>)Session["infoPprSelected"];
            IList<PrePurchaseRequestInfo> infoPprSeq = bll.GetDistinctSeq(infoPprSelected);
            string ppr_seq_text = "";
            DateTime pr_date;
            string pr_name;
            string pr_reason;
            int pc_rule_seq;
            int ppr_type_seq;
            int pc_type_seq;
            int year_type_seq;
            int bgm_year;
            DateTime? req_date = null;
            Nullable<int> req_duration = null;
            Nullable<int> dur_type_seq = null; 
            Nullable<int> dur_count_seq = null;
            int pr_emp_seq;

            Boolean IsExist;
            IList<int> PprItemSeq = new List<int>();

            if (infoPprSeq.Count > 0)
            {
                for (int i = 0; i < infoPprSeq.Count; i++)
                {
                    if (i == 0)
                    {
                        ppr_seq_text = infoPprSeq[i].Seq.ToString();
                    }
                    else
                    {
                        ppr_seq_text += ";" + infoPprSeq[i].Seq.ToString();
                    }
                }
            }

            if (infoPprSelected.Count > 0)
            {
                for (int i = 0; i < infoPprSelected.Count; i++)
                {
                    PprItemSeq.Add(Convert.ToInt32(infoPprSelected[i].InfoPprItem.Seq));
                }
            }

            pr_date = Convert.ToDateTime(txtDate.TextWithLiterals);
            pr_name = txtName.Text;
            pr_reason = txtReason.Text;
            pc_rule_seq = Convert.ToInt32(infoPprSelected[0].InfoPurchaseRule.Seq);
            ppr_type_seq = Convert.ToInt32(infoPprSelected[0].InfoPprType.Seq);
            pc_type_seq = Convert.ToInt32(infoPprSelected[0].InfoPurchaseType.Seq);
            year_type_seq = Convert.ToInt32(infoPprSelected[0].InfoYearType.Seq);
            bgm_year = Convert.ToInt32(infoPprSelected[0].Year);
            if (rdbDuration.Checked)
            {
                req_duration = (txtDurationReq.Text != "") ? (Nullable<int>)Convert.ToInt32(txtDurationReq.Text) : null;
                dur_type_seq = (cbDurationType.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbDurationType.SelectedValue.ToString()) : null;
                dur_count_seq = (cbDurationCount.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbDurationCount.SelectedValue.ToString()) : null;
            }
            else
            {
                req_date = (txtDateReq.Text != "") ? (DateTime?)Convert.ToDateTime(txtDateReq.TextWithLiterals) : null;
            }

            pr_emp_seq = Convert.ToInt32(cbOperationName.SelectedValue.ToString());

            try
            {
                bllCollectReq.CollectRequestItem(ppr_seq_text, PprItemSeq, pr_date, pr_name,
                    pr_reason, pc_rule_seq, ppr_type_seq, pc_type_seq, year_type_seq,
                    bgm_year, req_date, req_duration, dur_type_seq, dur_count_seq,
                    pr_emp_seq);
                RadManager1.ResponseScripts.Add(@"CloseWindow();");
                RadManager1.Alert("รวบรวมรายการเรียบร้อยแล้ว");

            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
            }

        }
    }
}
